package com.example.zengyi

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar

class MainActivity : AppCompatActivity() {

    private lateinit var minEditText: EditText
    private lateinit var maxEditText: EditText
    private lateinit var calculateButton: Button
    private lateinit var stopButton: Button
    private lateinit var dbHelper: PrimeNumberHelper
    private var calculationThread: Thread? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化 Toolbar
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        minEditText = findViewById(R.id.minEditText)
        maxEditText = findViewById(R.id.maxEditText)
        calculateButton = findViewById(R.id.calculateButton)
        stopButton = findViewById(R.id.stopButton)

        dbHelper = PrimeNumberHelper(this)

        calculateButton.setOnClickListener { startCalculation() }
        stopButton.setOnClickListener { stopCalculation() }
    }

    private fun startCalculation() {
        val min = minEditText.text.toString().toIntOrNull() ?: 0
        val max = maxEditText.text.toString().toIntOrNull() ?: 0

        calculationThread = Thread {
            for (i in min..max) {
                if (isPrime(i)) {
                    dbHelper.insertPrime(i)
                }
                if (Thread.currentThread().isInterrupted) {
                    break
                }
            }
        }
        calculationThread?.start()
    }

    private fun stopCalculation() {
        calculationThread?.takeIf { it.isAlive }?.interrupt()
    }

    private fun isPrime(number: Int): Boolean {
        if (number <= 1) return false
        var i = 2
        while (i * i <= number) {
            if (number % i == 0) return false
            i++
        }
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.menu_history) {
            val intent = Intent(this, HistoryActivity::class.java)
            startActivity(intent)
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}